package com.xiaoxing.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.google.gson.Gson;
import com.qiniu.common.QiniuException;
import com.qiniu.http.Response;
import com.qiniu.storage.Configuration;
import com.qiniu.storage.Region;
import com.qiniu.storage.UploadManager;
import com.qiniu.storage.model.DefaultPutRet;
import com.qiniu.util.Auth;
import com.xiaoxing.domain.ResponseResult;
import com.xiaoxing.domain.entity.User;
import com.xiaoxing.enums.AppHttpCodeEnum;
import com.xiaoxing.exception.SystemException;
import com.xiaoxing.service.UploadService;
import com.xiaoxing.service.UserService;
import com.xiaoxing.utils.PathUtils;
import com.xiaoxing.utils.SecurityUtils;
import lombok.Data;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.multipart.MultipartFile;

import java.io.InputStream;

/**
 *
 *   上传到oss的实现类
 *
 * **/
@Service
@Data
@ConfigurationProperties(prefix = "oss")
public class OssUploadService implements UploadService {

    @Autowired
    private UserService userService;

    private String accessKey;
    private String secretKey;
    private String bucket;

    @Override
    @Transactional
    public ResponseResult uploadImg(MultipartFile img,String UserId) {
        //1.判断文件类型
        //获取原始文件名
        String originalFilename = img.getOriginalFilename();
        //对原始文件名进行判断
        if(!originalFilename.endsWith(".png")&&!originalFilename.endsWith(".jpg")){
            throw new SystemException(AppHttpCodeEnum.FILE_TYPE_ERROR);
        }

        //如果判断通过上传文件到OSS
        String filePath = PathUtils.generateFilePath(originalFilename);
        String url = uploadOss(img,filePath,UserId);//  2099/2/3/wqeqeqe.png
        return ResponseResult.okResult(url);
    }
    private String uploadOss(MultipartFile imgFile, String filePath,String UserId){
        //构造一个带指定 Region 对象的配置类
        Configuration cfg = new Configuration(Region.autoRegion());
        //...其他参数参考类注释
        UploadManager uploadManager = new UploadManager(cfg);
        //默认不指定key的情况下，以文件内容的hash值作为文件名
        String key = filePath;
        try {
            InputStream inputStream = imgFile.getInputStream();
            Auth auth = Auth.create(accessKey, secretKey);
            String upToken = auth.uploadToken(bucket);
            try {
                Response response = uploadManager.put(inputStream,key,upToken,null, null);
                //解析上传成功的结果
                DefaultPutRet putRet = new Gson().fromJson(response.bodyString(), DefaultPutRet.class);
                System.out.println(putRet.key);
                System.out.println(putRet.hash);
                //得到外联（域名+key）
                String url= "http://sdexbjzh8.sabkt.gdipper.com/"+key;
                //更新用户头像地址
                LambdaQueryWrapper<User>wrapper=new LambdaQueryWrapper<User>();
                long num = Long.parseLong(UserId);
                wrapper.eq(User::getId,num);
                User one = userService.getOne(wrapper);
                one.setAvatar(url);
                userService.updateById(one);

            } catch (QiniuException ex) {
                ex.printStackTrace();
            }
        } catch (Exception ex) {
            ex.printStackTrace();
        }
        return "www";
    }
}
